﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using VueShopApi.Common;
using VueShopApi.Dtos;
using VueShopApi.Entities;
using VueShopApi.Common.Extensions;

namespace VueShopApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MenusController : AuthorizeController
    {
        private readonly ILogger<MenusController> _logger;
        private readonly IFreeSql _context;

        public MenusController(ILogger<MenusController> logger, IFreeSql context)
        {
            _logger = logger;
            _context = context;
        }

        /// <summary>
        /// 获取左侧菜单数据
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Get()
        {
            // SELECT * FROM sp_permission_api as api LEFT JOIN sp_permission as main ON main.ps_id = api.ps_id WHERE main.ps_id is not null
            var permissions = _context.Select<SpPermissionApi, SpPermission>()
                .LeftJoin((api, main) => main.PsId == api.PsId)
                .ToList<PermissionApiIncludePermissionDto>();

            var roleId = HttpContext.GetClaimsPrincipal().RoleId;
            if (roleId == 0)
            {
                return ServerResponse.Yes(GetRoleMenus(permissions, roleId, new List<int>()));
            }

            var role = await _context.Select<SpRole>(roleId).ToOneAsync();
            if (role == null)
                return ServerResponse.No("无权限访问");

            var rolePermissionIds = role.PsIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(r => Convert.ToInt32(r)).ToList();
            return ServerResponse.Yes(GetRoleMenus(permissions, roleId, rolePermissionIds));
        }
    }
}
